var form;
var index; //组织机构树弹出层的索引
var tableIns;
var ctxPath = '/'
$(function () {
    layui.config({
        base: ctxPath + 'lib/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index'//主入口模块
    }).use(['index', 'table', 'form', 'tree', 'laydate'], function () {
        // initRoleSelect();
        var table = layui.table;
        form = layui.form;
        tree = layui.tree;
        var laydate = layui.laydate;
        // 渲染表格
        tableIns = table.render({
            elem: '#table',
            toolbar: '#table-title',
            url: 'userPager',
            page: true,
            cols: [[
                {type: 'numbers'},
                {field: 'loginname', title: '用户名', align: 'center'},
                {field: 'name', title: '用户姓名', align: 'center'},
                {field: 'zhyxq', title: '账号有效期', align: 'center'},
                {field: 'mmyxq', title: '密码有效期', align: 'center'},
                {field: 'status', title: '用户状态', align: 'center', templet: '#islock'},
                {field: 'right', title: '操作', toolbar: '#table-toolbar', align: 'center'},
            ]],
            done: function (res, curr, count) {
                // merge(res);
                // $('tr').css({'background-color': '#009688', 'color': '#fff'});//表头样式修改
                var that = this.elem.next();
                var temp = res.data;
                for(var index=0; index < temp.length; index++){
                    var item = temp[index];
                    // var jyw = hex_md5(item.loginname + item.name + item.sfzhm + item.status);
                    if (item.isupdate === 1) {
                        var tr = that.find(".layui-table-box tbody tr[data-index='" + index + "']");
                        tr.css("background-color", "red");
                        tr.find(".laytable-cell-1-0-9").css("color","red");
                    }
                };
            },
            where: {
                name: $("#nameSearch").val(),
                loginname: $("#loginnameSearch").val()
            },
            request: {
                pageName: 'page' //页码的参数名称，默认：page
                , limitName: 'limit' //每页数据量的参数名，默认：limit
            }
        });
        //执行一个laydate实例
        laydate.render({
            elem: '#zhyxq' //指定元素
        });
        //执行一个laydate实例
        laydate.render({
            elem: '#mmyxq' //指定元素
        });
        //监听行工具事件
        table.on('tool(table)', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                openDel(obj)
            } else if (obj.event === 'edit') {
                openEdit(data)
            }
        });
        initRoleSelect()
        //监听提交
        form.on('submit(searchSubmit)', function () {
            tableIns.reload({
                where: {
                    name: $("#nameSearch").val(),
                    loginname: $("#loginnameSearch").val()
                },
                page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
            return false;
        });
        //监听是否启用状态操作
        form.on('switch(islock)', function (obj) {
            setUserStatus(obj, this.value, this.name, obj.elem.checked);
        });
        form.on('submit(submitUser)', function (data) {
            userSubmit($("#oper").val())
        })

    });
})
function submitCancel() {
    layer.closeAll()

}

// function initRoleSelect() {
//     $.ajax({
//         type: "GET",
//         url: ctxPath + "system/role/roleList",
//         success: function (res) {
//             var data = res.obj;
//             for (var i = 0; i < data.length; i++) {
//                 $("#role_id").append("<option value='" + data[i].id + "'>" + data[i].name + "</option>")
//             }
//             renderForm();
//         }
//     });
// }
/**
 * 删除用户
 * @param obj
 */
function openDel(obj) {
    var data = obj.data;
    layer.confirm('您确定要删除' + data.name + '用户么', function () {
        $.ajax({
            type: "DELETE",
            data: {
                "id": data.id
            },
            url: ctxPath + "system/user/userInfo",
            complete: function () {
                tableReload()
            }

        });
    });
}

function tableReload() {
    tableIns.reload({
        page: {
            curr: 1 //重新从第 1 页开始
        }
    });
}
/**
 * 打开编辑窗口
 */
function openAdd() {
    layer.open({
        type: 1,
        title: "用户管理",
        fixed: false,
        resize: false,
        shadeClose: true,
        area: ['700px', '500px'],
        content: $('#userEdit'),
        success: function () {
            $("#oper").val("0")
        },
        end: function () {
            cleanForm("userForm");
            tableReload();
        }
    })
}

/**
 * 打开编辑窗口
 * @param data layui中保存的table中的对应的此条信息
 */
function openEdit(data) {
    layer.open({
        type: 1,
        title: "用户管理",
        fixed: false,
        resize: false,
        shadeClose: true,
        area: ['700px', '500px'],
        content: $('#userEdit'),
        success: function () {
            $.get(ctxPath + "system/organization/name", {"cyqxh": data.organ}, function (res) {
                $("#organName").val(res.obj)
            });
            form.val('userForm', data);
            renderForm()
            $("#oper").val("1")
        }, end: function () {
            cleanForm("userForm")
            tableReload();
        }
    });
}

/**
 * 提交user表单信息
 */
function userSubmit(oper) {
    var type = oper == "0" ? "POST" : "PUT";
    $.ajax({
        type: type,
        data: $("#userForm").serialize(),
        url: ctxPath + "system/user/userInfo"
    });
}
/**
 * 点击重置密码
 */
function resetPassword(oper) {
    //console.log(modify_pwd)
    var modify_pwd = serializeObject($("#userForm"));
    layer.confirm('您确定要重置用户密码吗？', function () {
        $.ajax({
            type: "PUT",
            data: modify_pwd,
            url: ctxPath + "system/user/resetPassword",
            success: function (result) {
                console.log(result)
                if (result.code == "1") {
                    layer.msg("重置成功！！");
                }else {
                    $('#oldpwderr').html(result.message)
                    $('#oldpwderr').css('color','red')
                }
            }
        });
    });
}

//设置用户状态
function setUserStatus(obj, id, name, checked) {
    var status = checked ? 5 : 1;
    var ParaIsLock = checked ? "启用" : "停用";
    //用户状态
    layer.confirm('您确定要把用户：' + name + '设置为' + ParaIsLock + '状态吗？', {
        btn: ['确认', '返回'] //按钮
        //点击关闭按钮事件
        , cancel: function () {
            tableReload()
        }
    }, function () {
        $.ajax({
            type: "PUT",
            data: {"id": id, "status": status},
            url: ctxPath + "system/user/status",
            complete: function () {
                tableReload()
            }
        });
    }, function () {
        tableReload()
    });
}

/**
 * 构建组织机构树
 */
function buildOrganTree() {
    $.ajax({
        type: "GET",
        url: ctxPath + "system/organization/treeInfo",
        success: function (result) {
            if (result.code == "1") {
                var data = result.obj
                tree.render({
                    elem: '#organTree',  //绑定元素
                    data: data,
                    id: 'treeId',
                    onlyIconControl: true, //设置仅选中节点图标时才会伸缩
                    click: function (obj) {
                        $("#organ").val(obj.data.id);
                        $("#organName").val(obj.data.title);  //将选中的机构名回显到表单
                        layer.close(index)  //关闭组织机构弹出层
                    }
                });
            } else {
                layer.alert(result.msg)
            }
        }
    });
}

/**
 * 打开组织机构树弹出层
 */
function openOrganTree() {
    index = layer.open({
        type: 1,
        title: "选择机构",
        fixed: false,
        resize: false,
        shadeClose: true,
        area: ['20%', '60%'],
        content: $('#organDiv'),
        success: function () {
            buildOrganTree();  //构建组织机构树
        }
    });
}
function initRoleSelect() {
    $.ajax({
        type: "GET",
        url: ctxPath + "system/role/roleList",
        success: function (res) {
            var data = res.obj;
            for (var i = 0; i < data.length; i++) {
                $("#role_id").append("<option value='" + data[i].id + "'>" + data[i].name + "</option>")
            }
            renderForm();
        }
    });
}
